package org.ttitfly.ttcore.service.account;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public class SSAccessDecisionManager implements AccessDecisionManager {
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		Iterator<ConfigAttribute> iter = configAttributes.iterator();
		while (iter.hasNext()) {
			ConfigAttribute configAttribute = iter.next();
			// 该资源需要何种权限
			String needRole = ((SecurityConfig) configAttribute).getAttribute();
			for (GrantedAuthority grantedAuthority : authentication
					.getAuthorities()) {
				// 用户具备的权限
				String ownRole = grantedAuthority.getAuthority();
				if (needRole.equals(ownRole)) {
					return;
				}
			}
		}
		throw new AccessDeniedException("authority is denied");
	}

	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}
}
